package com.android.project.framework.util;

import java.util.Date;

import com.android.project.framework.impl.GLGame;
import com.android.project.games.Settings;


import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;

import android.util.Log;

public class TweetsActivity  {
	
	static final String consumerKey = "sQQQLcrxI9Xna1oOx6o3zg";
	static final String consumerSecret = "xZ4pJ13iM5lb294xFSLpUU5ZmpU51BuElVo5Oh9xY";
	String CALLBACK_URL = "wordsChain://tweet";
	static CommonsHttpOAuthConsumer consumer;
	static OAuthProvider provider;
	static TwitterApplication t;
	Twitter twitter;
	GLGame game;
	
	
	public TweetsActivity(GLGame g){
		game = g;
		t = new TwitterApplication();	
		
        
		 
	}
	public  AccessToken checkForSavedLogin() {
		// TODO Auto-generated method stub
		AccessToken a = getAccessToken();
		if (a==null) 
		{
	
			Log.d("checkSaved", "token null");
			Settings.twitter = false;
	        Settings.save(game.getFileIO());
		
			return null;
		}
			
		twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(consumerKey, consumerSecret);
		twitter.setOAuthAccessToken(a);
		Settings.twitter = true;
		Settings.save(game.getFileIO());
		return a;
		
		
	}


	/*public void getConsumerProvider() {
		OAuthProvider p = t.getProvider();
		if (p!=null){
			provider = p;
		}
		CommonsHttpOAuthConsumer c = t.getConsumer();
		if (c!=null){
			consumer = c;
		}
	}*/

	
	public AccessToken getAccessToken() {
		SharedPreferences settings = game.getSharedPreferences("TwitterLogin", 0);
		String token = settings.getString("accessTokenToken", "");
		String tokenSecret = settings.getString("accessTokenSecret", "");
		Log.d("getAccessToken!!" , token);
		if (token!=null && tokenSecret!=null && !"".equals(tokenSecret) && !"".equals(token)){
			return new AccessToken(token, tokenSecret);
		}
		return null;
	}

	public void askOAuth() {
		try {
			
			
			Log.d("twitter" , "askOauth");
			consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
			provider = new DefaultOAuthProvider("http://api.twitter.com/oauth/request_token", 
					"http://api.twitter.com/oauth/access_token", 
					"http://api.twitter.com/oauth/authorize");
			String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
			
			setConsumerProvider();
			
			game.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
			
		
			
		} catch (Exception e) {
			
		}
	}


		
	private void setConsumerProvider() {
	
	
		if (provider!=null){
			t.setProvider(provider);
		}
		if (consumer!=null){
			t.setConsumer(consumer);
		}
	}

	/*public Twitter getTwitter() {
		return twitter;
	}
	
	public void setTwitter(Twitter twitter) {
		this.twitter = twitter;
	}
	*/
	
	public static TwitterApplication getT() {
		return t;
	}
	public static void setT(TwitterApplication t) {
		TweetsActivity.t = t;
	}
	
	public static String getConsumerkey() {
		return consumerKey;
	}
	public static String getConsumersecret() {
		return consumerSecret;
	}
	
	public void resume(){
		if (game.getIntent()!=null && game.getIntent().getData()!=null){
			Uri uri = game.getIntent().getData();
			if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
				String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
				try {
					// this will populate token and token_secret in consumer
					Log.d("RESUMING!!" , verifier);
					//provider = TweetsActivity.getT().getProvider();
					//consumer =TweetsActivity.getT().getConsumer();
					if(consumer == null){
						Log.d("RESUMING!!" , "null");
					}
					//Log.d("RESUMING!!" , " " + consumer.getConsumerKey());
					provider.retrieveAccessToken(consumer, verifier);

					// Get Access Token and persist it
					AccessToken a = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
					storeAccessToken(a);

					// initialize Twitter4J
					twitter = new TwitterFactory().getInstance();
					twitter.setOAuthConsumer(TweetsActivity.getConsumerkey(), TweetsActivity.getConsumersecret());
					twitter.setOAuthAccessToken(a);
					
					Settings.twitter = true;
					Settings.save(game.getFileIO());
					Log.d("Login", "Twitter Initialised");

					//startFirstActivity();

				} catch (Exception e) {
					//Log.e(APP, e.getMessage());
					e.printStackTrace();
					
				}
			}
		}
	}
	

	private void storeAccessToken(AccessToken a) {
		SharedPreferences settings = game.getSharedPreferences("TwitterLogin", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("accessTokenToken", a.getToken());
		editor.putString("accessTokenSecret", a.getTokenSecret());
		
		editor.commit();
	}
	
	public void tweet(String score){
		  Date d = new Date(System.currentTimeMillis());
		
		  String tweet = "Ho appena giocato a Words Chain! Ho totalizzato il punteggio di " + score ;
		  
		  Log.d("tweet", "mandato");
	      // send the tweet
	      try {
				twitter.updateStatus(tweet);
			} catch (TwitterException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
}
